package com.onion.utils.utils;

import java.lang.reflect.Field;
import java.util.*;

public class ClazzUtils {

    public static Class<?> getClazz(String clazzName) {
        try {
            return Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T newInstance(Class<T> clazz){
        try {
            return clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static Field[] getDeclaredFields(Class<?> clazz){
        return clazz.getDeclaredFields();
    }

    public static List<Field> getAllFields(Class<?> clazz){
        List<Field> fieldList = new ArrayList<>();
        Set<String> fieldNameSet = new HashSet<>();
        Class<?> curClazz = clazz;
        while(curClazz!=null && !curClazz.getName().equals("java.lang.Object")){
            for(Field curField : curClazz.getDeclaredFields()){
                if(!fieldNameSet.contains(curField.getName())){
                    fieldList.add(curField);
                    fieldNameSet.add(curField.getName());
                }
            }
            curClazz = curClazz.getSuperclass();
        }
        return fieldList;
    }

}